/***************************************************************************
 *   Copyright (C) 2008 by JBox systems
 *   gabi@shaargiora.co.il
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 ***************************************************************************/

#include "controller.h"
#include "memory.h"

Controller::Controller(QObject *parent):
	QObject(parent),
	downloader(NULL) {
	connectController();
}

Controller::~Controller() {

}

void Controller::downloadVersions(std::vector<Version> versions) {
	this->versions = versions;
	m_keep_downloading = true;
	downloadNext();
}

void Controller::connectController() {
	connect(this, SIGNAL(abortDownloads()), this, SLOT(preventNextDownload()));
}

void Controller::downloadNext() {
	if (versions.size() == 0) {
		emit downloadsFinished();
		return;
	}

	if (!m_keep_downloading) {
		emit downloadsAborted();
		return;
	}

	Version version = versions.front();
	versions.erase(versions.begin(), versions.begin()+1);
	downloadVersion(version);
}

void Controller::downloadVersion(Version &version) {
	if (downloader) {
		disconnect(this, 0, downloader, 0);
		disconnect(downloader);
		DELETE(downloader);
	}
	downloader = new Downloader(version.url(), version.path(), this);

	// Make connections to controller.
	connect(this, SIGNAL(abortDownloads()), downloader, SLOT(cancelDownload()));
	connect(downloader, SIGNAL(downloadFinished(bool)), this, SLOT(downloadNext()));
	connect(downloader, SIGNAL(dataReadProgress(int, int)), this, SIGNAL(dataReadProgress(int, int)));

	emit status(QString("Downloading %1 %2").arg(QString(version.name().c_str())).arg(QString(version.version().c_str())));
}
